<template>
  <div class="space-y-6">
    <!-- 面包屑导航 -->
    <nav class="text-sm text-gray-500" aria-label="Breadcrumb">
      首页 &gt; 提示词库 &gt; {{ isEditing ? '编辑提示词' : '新建提示词' }}
    </nav>

    <!-- 标题栏 -->
    <div class="flex items-center justify-between">
      <div class="flex-1 max-w-md">
        <Input v-model="formData.title" label="" placeholder="请输入提示词名称" :error="validationErrors.title" />
      </div>
      <div class="flex items-center gap-2">
        <span v-if="isSaving" class="text-xs text-gray-500">保存中...</span>
        <span v-else-if="lastSavedAt" class="text-xs text-gray-500">已保存于 {{ lastSavedAt }}</span>
        <Button @click="handleSave" :disabled="isSaving">保存</Button>
        <Button variant="ghost" @click="openTestDialog">测试</Button>
        <Button variant="success" @click="handlePublish" :disabled="!canPublish">发布</Button>
      </div>
    </div>

    <!-- 表单错误提示 -->
    <div v-if="hasValidationErrors" class="p-3 bg-red-50 border border-red-200 rounded-card text-sm text-red-700">
      <div class="font-medium mb-1">请修正以下错误：</div>
      <ul class="list-disc list-inside space-y-1">
        <li v-for="error in flatValidationErrors" :key="error">{{ error }}</li>
      </ul>
    </div>

    <!-- 元数据表单 -->
    <Card title="基本信息">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Select 
          v-model="formData.category" 
          label="分类" 
          :options="categoryOptions"
          :error="validationErrors.category"
        />
        <div>
          <label class="text-xs text-gray-500 block mb-1">标签</label>
          <div class="flex flex-wrap gap-1 mb-2">
            <Tag 
              v-for="tag in formData.tags" 
              :key="tag" 
              :text="`#${tag}`" 
              :closable="true" 
              @close="removeTag(tag)" 
            />
          </div>
          <div class="flex gap-2">
            <Input 
              v-model="newTag" 
              placeholder="添加标签" 
              class="flex-1"
              @keydown.enter="addTag"
            />
            <Button size="sm" variant="ghost" @click="addTag">添加</Button>
          </div>
          <div v-if="validationErrors.tags" class="text-xs text-red-600 mt-1">{{ validationErrors.tags }}</div>
        </div>
      </div>
      <div class="mt-4">
        <Input 
          v-model="formData.description" 
          label="描述" 
          placeholder="请简要描述这个提示词的用途和特点"
          :error="validationErrors.description"
        />
      </div>
    </Card>

    <!-- 提示词编辑区 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- 编辑器 -->
      <div class="space-y-4">
        <Card title="System Prompt">
          <div>
            <textarea 
              ref="systemTextarea"
              v-model="formData.systemPrompt" 
              class="w-full h-40 border rounded-card p-3 resize-none" 
              :class="{ 'border-red-300': validationErrors.systemPrompt }"
              placeholder="您是一个专业的AI助手，擅长..."
            />
            <div v-if="validationErrors.systemPrompt" class="text-xs text-red-600 mt-1">{{ validationErrors.systemPrompt }}</div>
            <div class="text-xs text-gray-500 mt-1">字符数: {{ formData.systemPrompt.length }}/2000</div>
          </div>
        </Card>
        
        <Card title="User Prompt">
          <div>
            <textarea 
              ref="userTextarea"
              v-model="formData.userPrompt" 
              class="w-full h-40 border rounded-card p-3 resize-none" 
              :class="{ 'border-red-300': validationErrors.userPrompt }"
              placeholder="请针对{topic}主题，以{style}的风格，写一篇约{length}字的文章"
            />
            <div v-if="validationErrors.userPrompt" class="text-xs text-red-600 mt-1">{{ validationErrors.userPrompt }}</div>
            <div class="text-xs text-gray-500 mt-1">
              字符数: {{ formData.userPrompt.length }}/2000 | 提示：使用 {变量名} 来定义可替换的变量
            </div>
          </div>
        </Card>
      </div>

      <!-- 变量管理 -->
      <div class="space-y-4">
        <Card title="变量定义">
          <div class="space-y-3">
            <div v-for="(variable, index) in formData.variables" :key="`var-${index}`" class="space-y-2">
              <div class="grid grid-cols-12 gap-2 items-end">
                <div class="col-span-4">
                  <Input 
                    v-model="variable.name" 
                    placeholder="变量名" 
                    :error="validationErrors.variables?.[index]?.name"
                  />
                </div>
                <div class="col-span-3">
                  <Select 
                    v-model="variable.type" 
                    :options="['string', 'number', 'boolean', 'array']"
                    :error="validationErrors.variables?.[index]?.type"
                  />
                </div>
                <div class="col-span-4">
                  <Input 
                    v-model="variable.example" 
                    placeholder="示例值" 
                    :error="validationErrors.variables?.[index]?.example"
                  />
                </div>
                <Button size="sm" variant="danger" @click="removeVariable(index)" class="col-span-1">×</Button>
              </div>
              <div class="grid grid-cols-12 gap-2">
                <div class="col-span-11">
                  <Input 
                    v-model="variable.description" 
                    placeholder="变量说明（可选）" 
                    class="text-xs"
                  />
                </div>
              </div>
            </div>
            <Button size="sm" variant="ghost" @click="addVariable" class="w-full">+ 添加变量</Button>
            <div v-if="validationErrors.variablesGeneral" class="text-xs text-red-600">{{ validationErrors.variablesGeneral }}</div>
          </div>
        </Card>

        <!-- 模型配置 -->
        <Card title="测试配置">
          <div class="space-y-3">
            <Select 
              v-model="testConfig.model" 
              label="模型" 
              :options="modelOptions" 
            />
            <div>
              <label class="text-xs text-gray-500 block mb-1">温度: {{ testConfig.temperature }}</label>
              <input 
                v-model.number="testConfig.temperature" 
                type="range" 
                min="0" 
                max="1" 
                step="0.1" 
                class="w-full"
              />
            </div>
            <div>
              <Input 
                v-model.number="testConfig.maxTokens" 
                label="最大输出长度" 
                placeholder="1000" 
                type="number"
              />
            </div>
            <div>
              <label class="text-xs text-gray-500 block mb-1">Top P: {{ testConfig.topP }}</label>
              <input 
                v-model.number="testConfig.topP" 
                type="range" 
                min="0" 
                max="1" 
                step="0.1" 
                class="w-full"
              />
            </div>
            <Button @click="openTestDialog" :disabled="!canTest" class="w-full">
              配置并运行测试
            </Button>
          </div>
        </Card>
      </div>
    </div>

    <!-- 测试结果 -->
    <Card title="测试结果" v-if="testResult || isTestRunning">
      <div v-if="isTestRunning" class="text-center py-8 text-gray-500">
        <div class="animate-pulse">测试中，请稍候...</div>
        <div class="text-xs mt-2">模型: {{ testConfig.model }} | 温度: {{ testConfig.temperature }}</div>
      </div>
      <div v-else-if="testResult" class="space-y-3">
        <div class="text-sm text-gray-600 flex flex-wrap gap-4">
          <span>模型: {{ testResult.config.model }}</span>
          <span>温度: {{ testResult.config.temperature }}</span>
          <span>最大长度: {{ testResult.config.maxTokens }}</span>
          <span>执行时间: {{ testResult.duration }}ms</span>
          <span>Token消耗: {{ testResult.tokens }}</span>
        </div>
        <div class="bg-gray-50 p-4 rounded border text-sm leading-relaxed">
          {{ testResult.response }}
        </div>
        <div class="flex gap-2">
          <Button size="sm" variant="ghost" @click="copyResult">复制结果</Button>
          <Button size="sm" variant="ghost" @click="saveAsTestCase">保存为测试用例</Button>
          <Button size="sm" variant="ghost" @click="runNewTest">重新测试</Button>
        </div>
      </div>
    </Card>

    <!-- 测试对话框 -->
    <div v-if="showTestDialog" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" @click="closeTestDialog">
      <div class="bg-white rounded-card p-6 w-full max-w-2xl max-h-[80vh] overflow-y-auto" @click.stop>
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-medium">配置测试参数</h3>
          <Button size="sm" variant="ghost" @click="closeTestDialog">×</Button>
        </div>
        
        <div class="space-y-4">
          <!-- 变量输入 -->
          <div v-if="formData.variables.length > 0">
            <h4 class="text-sm font-medium text-gray-700 mb-3">变量值</h4>
            <div class="space-y-3">
              <div v-for="(variable, index) in formData.variables" :key="`test-var-${index}`" class="grid grid-cols-3 gap-3 items-center">
                <div class="text-sm text-gray-600">{{ variable.name }}</div>
                <div class="text-xs text-gray-500">{{ variable.type }}</div>
                <Input 
                  v-model="testVariableValues[variable.name]" 
                  :placeholder="variable.example || `输入${variable.name}的值`"
                />
              </div>
            </div>
          </div>

          <!-- 预览 -->
          <div>
            <h4 class="text-sm font-medium text-gray-700 mb-2">最终提示词预览</h4>
            <div class="bg-gray-50 p-3 rounded border text-sm space-y-2">
              <div v-if="formData.systemPrompt">
                <div class="text-xs text-gray-500 mb-1">System:</div>
                <div class="font-mono">{{ processedSystemPrompt }}</div>
              </div>
              <div v-if="formData.userPrompt">
                <div class="text-xs text-gray-500 mb-1">User:</div>
                <div class="font-mono">{{ processedUserPrompt }}</div>
              </div>
            </div>
          </div>

          <!-- 测试按钮 -->
          <div class="flex gap-3 pt-3">
            <Button @click="runTest" :disabled="isTestRunning || !canRunTest" class="flex-1">
              {{ isTestRunning ? '测试中...' : '开始测试' }}
            </Button>
            <Button variant="ghost" @click="closeTestDialog">取消</Button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, reactive, provide, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Card, Button, Input, Select, Tag } from '../components/UI'

const router = useRouter()
const route = useRoute()

// 表单数据
const formData = ref({
  title: '',
  description: '',
  category: '',
  tags: [] as string[],
  systemPrompt: '',
  userPrompt: '',
  variables: [] as Array<{ 
    name: string; 
    type: string; 
    example: string; 
    description?: string;
    required?: boolean;
  }>
})

// 验证错误
const validationErrors = reactive<Record<string, any>>({})

// 编辑状态
const isEditing = computed(() => !!route.query.id)
const isSaving = ref(false)
const lastSavedAt = ref('')

// 标签管理
const newTag = ref('')

// 测试配置
const testConfig = ref({
  model: 'GPT-4',
  temperature: 0.7,
  maxTokens: 1000,
  topP: 0.9
})

const isTestRunning = ref(false)
const testResult = ref<{ 
  response: string; 
  duration: number; 
  tokens: number;
  config: any;
} | null>(null)

// 测试对话框
const showTestDialog = ref(false)
const testVariableValues = reactive<Record<string, string>>({})
const systemTextarea = ref<HTMLTextAreaElement | null>(null)
const userTextarea = ref<HTMLTextAreaElement | null>(null)

// 选项数据
const categoryOptions = ['客服', '内容创作', '代码开发', '数据分析', '翻译', '其他']
const modelOptions = ['GPT-4', 'GPT-3.5-turbo', 'Claude 3.5 Sonnet', 'Gemini Pro']

// 验证逻辑
const hasValidationErrors = computed(() => Object.keys(validationErrors).length > 0)
const flatValidationErrors = computed(() => {
  const errors: string[] = []
  Object.entries(validationErrors).forEach(([key, value]) => {
    if (typeof value === 'string') {
      errors.push(value)
    } else if (Array.isArray(value)) {
      value.forEach((item: any) => {
        if (typeof item === 'object') {
          Object.values(item).forEach((err: any) => {
            if (typeof err === 'string') errors.push(err)
          })
        }
      })
    }
  })
  return errors
})

function validateForm() {
  const errors: Record<string, any> = {}
  
  // 标题验证
  if (!formData.value.title.trim()) {
    errors.title = '请输入提示词名称'
  } else if (formData.value.title.length > 100) {
    errors.title = '标题不能超过100个字符'
  }
  
  // 分类验证
  if (!formData.value.category) {
    errors.category = '请选择分类'
  }
  
  // 描述验证
  if (formData.value.description && formData.value.description.length > 500) {
    errors.description = '描述不能超过500个字符'
  }
  
  // 提示词验证
  if (!formData.value.systemPrompt.trim() && !formData.value.userPrompt.trim()) {
    errors.systemPrompt = 'System Prompt 和 User Prompt 至少需要填写一个'
    errors.userPrompt = 'System Prompt 和 User Prompt 至少需要填写一个'
  }
  
  if (formData.value.systemPrompt.length > 2000) {
    errors.systemPrompt = 'System Prompt 不能超过2000个字符'
  }
  
  if (formData.value.userPrompt.length > 2000) {
    errors.userPrompt = 'User Prompt 不能超过2000个字符'
  }
  
  // 标签验证
  if (formData.value.tags.length > 10) {
    errors.tags = '标签数量不能超过10个'
  }
  
  // 变量验证
  const variableErrors: any[] = []
  const variableNames = new Set()
  
  formData.value.variables.forEach((variable, index) => {
    const varErrors: any = {}
    
    if (!variable.name.trim()) {
      varErrors.name = '变量名不能为空'
    } else if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(variable.name)) {
      varErrors.name = '变量名只能包含字母、数字和下划线，且不能以数字开头'
    } else if (variableNames.has(variable.name)) {
      varErrors.name = '变量名不能重复'
    } else {
      variableNames.add(variable.name)
    }
    
    if (!variable.type) {
      varErrors.type = '请选择变量类型'
    }
    
    if (!variable.example.trim()) {
      varErrors.example = '请提供示例值'
    }
    
    if (Object.keys(varErrors).length > 0) {
      variableErrors[index] = varErrors
    }
  })
  
  if (variableErrors.length > 0) {
    errors.variables = variableErrors
  }
  
  // 检查提示词中的变量是否已定义
  const promptText = `${formData.value.systemPrompt} ${formData.value.userPrompt}`
  const promptVariables = [...promptText.matchAll(/\{(\w+)\}/g)].map(match => match[1])
  const definedVariables = formData.value.variables.map(v => v.name)
  const undefinedVariables = promptVariables.filter(v => !definedVariables.includes(v))
  
  if (undefinedVariables.length > 0) {
    errors.variablesGeneral = `提示词中使用了未定义的变量: ${undefinedVariables.join(', ')}`
  }
  
  // 更新验证错误
  Object.keys(validationErrors).forEach(key => delete validationErrors[key])
  Object.assign(validationErrors, errors)
  
  return Object.keys(errors).length === 0
}

// 验证
const canPublish = computed(() => {
  return !hasValidationErrors.value &&
         !!formData.value.title.trim() &&
         !!formData.value.category &&
         (!!formData.value.systemPrompt.trim() || !!formData.value.userPrompt.trim())
})

const canTest = computed(() => {
  return formData.value.systemPrompt.trim() || formData.value.userPrompt.trim()
})

const canRunTest = computed(() => {
  if (!canTest.value) return false
  
  // 检查所有变量是否都有值
  for (const variable of formData.value.variables) {
    if (!testVariableValues[variable.name]?.trim()) {
      return false
    }
  }
  return true
})

// 处理变量替换
const processedSystemPrompt = computed(() => {
  return replaceVariables(formData.value.systemPrompt)
})

const processedUserPrompt = computed(() => {
  return replaceVariables(formData.value.userPrompt)
})

function replaceVariables(text: string) {
  let result = text
  Object.entries(testVariableValues).forEach(([name, value]) => {
    result = result.replace(new RegExp(`\\{${name}\\}`, 'g'), value)
  })
  return result
}

// 初始化数据
onMounted(() => {
  if (isEditing.value) {
    loadExistingData()
  } else {
    formData.value.variables = [
      { name: 'topic', type: 'string', example: 'AI发展趋势', description: '讨论的主题' }
    ]
    initTestVariableValues()
  }
})

function loadExistingData() {
  formData.value = {
    title: '客服对话模板',
    description: '专为客服场景设计的对话模板，包含常见问题处理和情感分析功能',
    category: '客服',
    tags: ['客服', '对话', 'AI'],
    systemPrompt: '您是一个专业的客服AI助手，擅长处理客户咨询和问题解决。请保持礼貌、耐心和专业的态度。',
    userPrompt: '客户咨询：{question}\n\n请针对上述咨询提供{style}的回复，控制在{length}字以内。',
    variables: [
      { name: 'question', type: 'string', example: '如何退换货？', description: '客户的具体问题' },
      { name: 'style', type: 'string', example: '友善专业', description: '回复的语调风格' },
      { name: 'length', type: 'number', example: '200', description: '回复字数限制' }
    ]
  }
  initTestVariableValues()
}

function initTestVariableValues() {
  formData.value.variables.forEach(variable => {
    testVariableValues[variable.name] = variable.example
  })
}

// 监听变量变化，同步测试值
watch(() => formData.value.variables, (newVars) => {
  newVars.forEach(variable => {
    if (!testVariableValues[variable.name]) {
      testVariableValues[variable.name] = variable.example
    }
  })
  
  // 清除已删除变量的测试值
  const currentNames = newVars.map(v => v.name)
  Object.keys(testVariableValues).forEach(name => {
    if (!currentNames.includes(name)) {
      delete testVariableValues[name]
    }
  })
}, { deep: true })

// 标签操作
function addTag() {
  const tag = newTag.value.trim()
  if (tag && !formData.value.tags.includes(tag)) {
    if (formData.value.tags.length >= 10) {
      return
    }
    formData.value.tags.push(tag)
    newTag.value = ''
    validateForm()
  }
}

function removeTag(tag: string) {
  const index = formData.value.tags.indexOf(tag)
  if (index > -1) {
    formData.value.tags.splice(index, 1)
    validateForm()
  }
}

// 变量操作
function addVariable() {
  formData.value.variables.push({ 
    name: '', 
    type: 'string', 
    example: '',
    description: ''
  })
}

function removeVariable(index: number) {
  const variable = formData.value.variables[index]
  if (variable) {
    delete testVariableValues[variable.name]
    formData.value.variables.splice(index, 1)
    validateForm()
  }
}

// 测试对话框
function openTestDialog() {
  if (!canTest.value) return
  showTestDialog.value = true
  initTestVariableValues()
}

function closeTestDialog() {
  showTestDialog.value = false
}

// 动作处理
async function handleSave() {
  if (!validateForm()) {
    return
  }
  
  isSaving.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    lastSavedAt.value = new Date().toLocaleTimeString()
    console.log('保存成功:', formData.value)
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    isSaving.value = false
  }
}

async function handlePublish() {
  if (!canPublish.value) return
  
  try {
    await handleSave()
    await new Promise(resolve => setTimeout(resolve, 500))
    console.log('发布成功')
    router.push('/library')
  } catch (error) {
    console.error('发布失败:', error)
  }
}

async function runTest() {
  if (!canRunTest.value) return
  
  isTestRunning.value = true
  testResult.value = null
  
  try {
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    const finalSystemPrompt = replaceVariables(formData.value.systemPrompt)
    const finalUserPrompt = replaceVariables(formData.value.userPrompt)
    
    testResult.value = {
      response: `基于您的提示词配置生成的回复：\n\n${finalUserPrompt}\n\n这是一个模拟的AI回复。在实际应用中，这里会显示根据处理后的System Prompt和User Prompt生成的真实AI响应。当前使用的变量值已经替换到最终的提示词中。`,
      duration: 1850,
      tokens: 156,
      config: { ...testConfig.value }
    }
    
    closeTestDialog()
  } catch (error) {
    console.error('测试失败:', error)
  } finally {
    isTestRunning.value = false
  }
}

function runNewTest() {
  openTestDialog()
}

function copyResult() {
  if (testResult.value) {
    navigator.clipboard.writeText(testResult.value.response)
  }
}

function saveAsTestCase() {
  // 实现保存测试用例逻辑
  console.log('保存测试用例')
}

function insertAtTextarea(el: HTMLTextAreaElement | null, field: 'systemPrompt'|'userPrompt', text: string) {
  const current = formData.value[field] ?? ''
  if (!el) {
    formData.value[field] = current + text
    validateForm()
    return
  }
  const start = el.selectionStart ?? current.length
  const end = el.selectionEnd ?? start
  formData.value[field] = current.slice(0, start) + text + current.slice(end)
  nextTick(() => {
    const pos = start + text.length
    el.focus()
    el.setSelectionRange(pos, pos)
  })
  validateForm()
}

// 实时验证
watch(formData, () => {
  validateForm()
}, { deep: true })

// 提供编辑器状态给子组件（AssistantPanel）
provide('editorState', {
  formData: computed(() => formData.value),
  isEditing: computed(() => isEditing.value),
  validationErrors: computed(() => validationErrors),
  addVariable,
  removeVariable,
  insertVariable: (position: 'system' | 'user', text: string) => {
    const fieldMap = {
      system: 'systemPrompt',
      user: 'userPrompt'
    } as const
    const field = fieldMap[position]
    const el = position === 'system' ? systemTextarea.value : userTextarea.value
    insertAtTextarea(el, field, text)
  }
})
</script>

<style scoped>
textarea {
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
}

.animate-pulse {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: .5;
  }
}
</style>